"use server";
import { db } from "@/lib/db";
import { signIn } from "@/auth";
import { getUserByEmail } from "@/data/user";
import { DEFAULT_LOGIN_REDIRECT } from "@/routes";
import { LoginSchema } from "@/schemas";
import { AuthError } from "next-auth";
import * as z from "zod";
import { generateTwoFactoryToken, generateVerificationToken } from "./token";
import { sendTwoFactoryEmail, sendVerificationEmail } from "@/lib/mail";
import { Code } from "@/common/code";
import { getTwoFactoryTokenByEmail } from "@/data/two-factory-token";
import { getTwoFactoryConfirmationByUserId } from "@/data/two-factory-confirmation";
export const login = async (values: z.infer<typeof LoginSchema>) => {
  const validateFilelds = LoginSchema.safeParse(values);
  if (!validateFilelds.success) {
    return { code: 1, data: ' error: "Invalid fields" ' };
  }
  const { email, password, code } = validateFilelds.data;

  // 实现邮箱验证
  const exeistingUser = await getUserByEmail(email);
  if (!exeistingUser || !exeistingUser.password || !exeistingUser.email) {
    return {
      code: 1,
      data: "Email does not exist!",
      message: "Email does not exist!",
    };
  }
  //  验证码登录
  if (exeistingUser.isEmailVerified) {
    if (code) {
      // 验证code
      const twoFactoryToken = await getTwoFactoryTokenByEmail(email);
      if (!twoFactoryToken) {
        return {
          code: Code.INVALID_FIELDS,
          data: "Invald code",
          message: "Invald code",
        };
      }
      if (twoFactoryToken.token !== code) {
        return {
          code: Code.INVALID_FIELDS,
          data: "Invald code",
          message: "Invald code",
        };
      }
      const hasExpire =
        new Date().getTime() > twoFactoryToken.expires.getTime();
      if (hasExpire) {
        return {
          code: Code.EXPIRE,
          data: "code expire",
          message: "code expire",
        };
      }

      // 删除Factorytoken
      await db.twoFactoryToken.delete({
        where: {
          id: twoFactoryToken.id,
        },
      });
      // 查看是否存有twoFactoryConfirmation
      const twoFactoryConfirmation = await getTwoFactoryConfirmationByUserId(
        exeistingUser.id
      );
      if (twoFactoryConfirmation) {
        await db.twoFactoryConfirmation.delete({
          where: {
            id: twoFactoryConfirmation.id,
          },
        });
      }
      // 创建twoFactoryConfirmation
      await db.twoFactoryConfirmation.create({
        data: {
          userId: exeistingUser.id,
        },
      });
    } else {
      const twoFactoryToken = await generateTwoFactoryToken(
        exeistingUser.email
      );
      // 发邮件
      await sendTwoFactoryEmail(twoFactoryToken.email, twoFactoryToken.token);
      return {
        code: Code.REDIRECT,
        data: "",
      };
    }
  } else {
    // 邮件登录
    if (
      !exeistingUser.emailVerified ||
      new Date().getTime() > exeistingUser.emailVerified!.getTime()
    ) {
      const verificationToken = await generateVerificationToken(
        exeistingUser.email
      );
      await sendVerificationEmail(email, verificationToken.token);
      return {
        code: Code.SUCCESS,
        data: "Confirmation email sent!",
      };
    }
  }

  try {
    await signIn("credentials", {
      email,
      password,
      redirectTo: DEFAULT_LOGIN_REDIRECT,
    });
    return { code: 0, data: "Success" };
  } catch (error) {
    if (error instanceof AuthError) {
      switch (error.type) {
        case "CredentialsSignin":
          return {
            code: Code.INVALID_FIELDS,
            data: "Invalid credentials",
            message: "Invalid credentials",
          };
        default:
          return {
            code: Code.SERVER_ERROR,
            data: "Server error",
            message: "Server error",
          };
      }
    }
    throw error;
  }
};
